﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using DataContracts;
using ServiceContracts;
using System.Configuration;

namespace Presention
{
    public class ServiceAgent:IDisposable
    {
        private IService _channel;

        private void GetChannel()
        {
            string channelConfig = ConfigurationManager.AppSettings["Channel"];
            if (string.IsNullOrEmpty(channelConfig) == false)
            {
                switch (channelConfig)
                {
                    case "Tcp":
                        _channel = new ChannelFactory<IService>("TcpClientEndPoint").CreateChannel();
                        break;
                    case "Http":
                        _channel = new ChannelFactory<IService>("HttpClientEndPoint").CreateChannel();
                        break;
                    default:
                        _channel = new ChannelFactory<IService>("HttpClientEndPoint").CreateChannel();
                        break;
                }
            }

        }

        public IService ServiceClient
        {
            get
            {
                if (_channel == null)
                {
                    GetChannel();
                }
                return _channel;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        private void Dispose(bool isDisposing)
        {
            if (isDisposing == true && _channel != null)
            {
                try
                {
                    if (((IClientChannel)_channel).State != CommunicationState.Faulted)
                    {
                        ((IClientChannel)_channel).Close();
                    }
                    else
                    {
                        ((IClientChannel)_channel).Abort();
                    }
                }
                catch (Exception exp)
                {
                    ((IClientChannel)_channel).Abort();
                    throw exp;
                }
                finally
                {
                    _channel = null;
                }
            }
        }
    }
}